package com.ky.home.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ky.common.param.NewsAdd;
import com.ky.common.vo.R;
import com.ky.home.entity.News;

import com.ky.home.mapper.NewsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 资讯表 前端控制器
 * </p>
 *
 * @author pl
 * @since 2024-06-17
 */
@RestController
@RequestMapping("/home")
public class NewsController {
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("/getNews")
    public R getNews() {
        List<News> news = newsMapper.selectList(null);
        if (news != null) {
            return R.ok(news);
        }
        return R.fail("查询失败");
    }

    @RequestMapping("/getNewsDetails/{id}")
    public R getNewsById(@PathVariable("id") int id) {
        News news = newsMapper.selectById(id);
        redisTemplate.opsForValue().set("newsId" , id);
        if (news != null) {
            return R.ok(news);
        }
        return R.fail("查询失败");
    }

    @RequestMapping("/searchNews/{value}")
    public R searchNews(@PathVariable("value") String value) {
        QueryWrapper<News> newsQueryWrapper = new QueryWrapper<>();
        newsQueryWrapper.like("title", value);
        List<News> news = newsMapper.selectList(newsQueryWrapper);
        if (news != null) {
            return R.ok(news);
        }
        return R.fail("查询失败");
    }

    @RequestMapping("/createNews")
    public R createNews(@RequestBody NewsAdd newsAdd) {
        News news = new News().setTitle(newsAdd.getTitle())
                .setContent(newsAdd.getContent())
                .setCategory(newsAdd.getCategory())
                .setImageUrl(newsAdd.getImageUrl())
                .setAuthor(newsAdd.getAuthor())
                .setPublishDate(new Date());
        if (newsMapper.insert(news) > 0) {
            return R.ok(news);
        }
        return R.fail("发布失败");
    }
    @RequestMapping("/addLikes")
    public R addLikes() {
        int newsId = (int) redisTemplate.opsForValue().get("newsId");
        News news = newsMapper.selectById(newsId);
        if (news != null) {
            news.setLikes(news.getLikes() + 1);
            newsMapper.updateById(news);
            return R.ok(news);
        }
        return R.fail("点赞失败");
    }
    @RequestMapping("/addCollects")
    public R addCollects() {
        int newsId = (int) redisTemplate.opsForValue().get("newsId");
        News news = newsMapper.selectById(newsId);
        if (news != null) {
            news.setCollects(news.getCollects() + 1);
            newsMapper.updateById(news);
            return R.ok(news);
        }
        return R.fail("收藏失败");
    }

}

